package myLearnjdk.jdk.nio.clientServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;

/**
 * 
 * @author yangcheng  
 * @date 2020年8月13日  
 * @version V1.0
 */
public class NioClient {
	public static void main(String[] args) {
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
		try {
			SocketChannel clientChannel = SocketChannel.open(address);
			
			
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			WritableByteChannel writeChannel = Channels.newChannel(System.out);
			//从输出流中获取channel
			/**
			 * 默认情况下read(buffer)为非阻塞方法，可以通过clientChannel.configureBlocking(true)
			 * 来将read方法变成阻塞式方法。
			 */
			while(true){
				if(clientChannel.read(buffer) == -1){
					break;
				}
				if(clientChannel.read(buffer) != 0){
					buffer.flip();//将指针归零
					writeChannel.write(buffer);
					buffer.clear();//清空buffer中的数据
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
